package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Sets;
import com.zhijian.medical.dao.local.SangerHschyq1Mapper;
import com.zhijian.medical.entity.dto.SangerHskzyqInsideDto;
import com.zhijian.medical.entity.dto.SangerHskzyqOutsideDto;
import com.zhijian.medical.entity.dto.SangerSjpzqPcrDto;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Sanger;
import com.zhijian.medical.entity.po.SangerHschyq1;
import com.zhijian.medical.entity.po.SangerSjpzq;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.SangerHschyq1SaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.SangerHschyq1SearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.SangerHschyq1Vo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.SangerStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.*;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 一代测序-核酸纯化一区 （普通PCR产物纯化）业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-12 14:41:02
 */
@Slf4j
@Service
public class SangerHschyq1ServiceImpl implements SangerHschyq1Service {

    @Autowired
    private SangerHschyq1Mapper mapper;

    @Autowired
    private SangerSjpzqService sangerSjpzqService;

    @Autowired
    private SangerService sangerService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public SangerHschyq1 selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public SangerHschyq1 selectBySangerId(Long sangerId) {
        return mapper.selectBySangerId(sangerId);
    }

    @Override
    public SangerHschyq1Vo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public SangerHschyq1Vo selectVoBySangerId(Long sangerId) {
        SangerHschyq1Vo sangerHschyq1Vo = mapper.selectVoBySangerId(sangerId);
        if (Objects.isNull(sangerHschyq1Vo)) {
            return null;
        }
        Sanger sanger = sangerService.selectById(sangerId);
        if (Objects.isNull(sanger)) {
            return null;
        }
        sangerHschyq1Vo.setResult(sanger.getStatus() > SangerStatusEnum.HSCHYQ1.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        sangerHschyq1Vo.setResultStr(sanger.getStatus() > SangerStatusEnum.HSCHYQ1.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        String chcwfywzjbhData = sangerHschyq1Vo.getChcwfywzjbhData();
        if (StringUtils.isNotBlank(chcwfywzjbhData)) {
            sangerHschyq1Vo.setChcwfywzjbhDataList(JsonUtil.toArray(chcwfywzjbhData, SangerSjpzqPcrDto.class));
        }
        String pcrData = sangerHschyq1Vo.getPcrData();
        if (StringUtils.isNotBlank(pcrData)) {
            sangerHschyq1Vo.setPcrDataList(JsonUtil.toArray(pcrData, SangerHskzyqOutsideDto.class));
        }
        return sangerHschyq1Vo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(SangerHschyq1 sangerHschyq1) {
        Date now = new Date();
        sangerHschyq1.setCreateTime(now);
        sangerHschyq1.setUpdateTime(now);
        sangerHschyq1.setSytmqj(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq1.setAzfzzsop010(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq1.setGcywyc(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq1.setDypcrfycx(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq1.setLxj(StatusEnum.NORMAL.getCode().byteValue());
        sangerHschyq1.setAqg(StatusEnum.NORMAL.getCode().byteValue());
        sangerHschyq1.setPcry(StatusEnum.NORMAL.getCode().byteValue());
        sangerHschyq1.setQjjzwzssygztm(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq1.setQjyyq(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq1.setQjlxj(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerHschyq1.setClsyfqw(StatusEnum.UN_NORMAL.getCode().byteValue());
        return mapper.insert(sangerHschyq1) > 0 ? sangerHschyq1.getId() : 0L;
    }

    @Override
    public boolean update(SangerHschyq1 sangerHschyq1) {
        Date now = new Date();
        sangerHschyq1.setUpdateTime(now);
        return mapper.updateByPrimaryKey(sangerHschyq1) != 0;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(SangerHschyq1SaveOrUpdateVo sangerHschyq1SaveOrUpdateVo) {
        Long sangerId = sangerHschyq1SaveOrUpdateVo.getSangerId();
        Sanger sanger = sangerService.selectById(sangerId);
        AssertUtil.notNull(sanger, "此实验不存在或者已被删除");
        if (sanger.getStatus() < SangerStatusEnum.HSCHYQ2.getCode().byteValue()) {
            //将实验的状态修改
            sangerService.updateByPrimaryKeySelective(Sanger.builder()
                    .id(sangerId)
                    .status(SangerStatusEnum.HSCHYQ2.getCode().byteValue())
                    .build());
        }
        SangerHschyq1 oldSangerHschyq1 = this.selectBySangerId(sangerId);
        List<SangerSjpzqPcrDto> chcwfywzjbhDataList = sangerHschyq1SaveOrUpdateVo.getChcwfywzjbhDataList();
        if (CollectionUtil.isNotEmpty(chcwfywzjbhDataList)) {
            sangerHschyq1SaveOrUpdateVo.setChcwfywzjbhData(JsonUtil.toString(chcwfywzjbhDataList));
        }

        List<SangerHskzyqOutsideDto> sangerHskzyqSaveOrUpdateVoDataList = sangerHschyq1SaveOrUpdateVo.getPcrDataList();
        if (CollectionUtil.isNotEmpty(sangerHskzyqSaveOrUpdateVoDataList)) {
            //如果传了表格数据，前端只会传编号，要把编号对应的分子病理号查出来，也就是去试剂配置区里查
            SangerSjpzq sangerSjpzq = sangerSjpzqService.selectBySangerId(sangerId);
            AssertUtil.notNull(sangerSjpzq, "还未完成试剂配置区");
            String pcrData = sangerSjpzq.getPcrData();
            AssertUtil.check(StringUtils.isBlank(pcrData), "还未完成试剂配置区-PCR反应液分装至各反应管，反应编号及检测项目");
            //试剂配置区的PCR的数据
            List<SangerSjpzqPcrDto> sangerSjpzqPcrDtoList = JsonUtil.toArray(pcrData, SangerSjpzqPcrDto.class);

            Set<Integer> set = Sets.newHashSet();
            sangerHskzyqSaveOrUpdateVoDataList.forEach(sangerHskzyqOutsideDto -> {
                List<List<SangerHskzyqInsideDto>> sangerHskzyqOutsideDtoData = sangerHskzyqOutsideDto.getData();
                if (CollectionUtil.isNotEmpty(sangerHskzyqOutsideDtoData)) {
                    sangerHskzyqOutsideDtoData.forEach(sangerHskzyqInsideDtos -> {
                        if (CollectionUtil.isNotEmpty(sangerHskzyqInsideDtos)) {
                            sangerHskzyqInsideDtos.stream().filter(s -> Objects.nonNull(s.getBh())).forEach(sangerHskzyqInsideDto -> {
                                //编号
                                Integer bh = sangerHskzyqInsideDto.getBh();
                                AssertUtil.check(!set.add(bh), "反应孔数据不允许有重复编号");
                                //筛选出编号一样的数据
                                SangerSjpzqPcrDto sangerSjpzqPcrDto = sangerSjpzqPcrDtoList.stream().filter(s -> s.getNumber().equals(bh)).findFirst().orElse(null);
                                sangerHskzyqInsideDto.setFzblh(Objects.nonNull(sangerSjpzqPcrDto) ? String.format("%s-%s-%s", sangerSjpzqPcrDto.getFzblh(), sangerSjpzqPcrDto.getProject(), sangerSjpzqPcrDto.getTurn()) : null);
                            });
                        }
                    });
                }
            });
            sangerHschyq1SaveOrUpdateVo.setPcrData(JsonUtil.toString(sangerHskzyqSaveOrUpdateVoDataList));
        }

        SangerHschyq1 dbParam = new SangerHschyq1();
        BeanUtils.copyProperties(sangerHschyq1SaveOrUpdateVo, dbParam);

        if (Objects.isNull(oldSangerHschyq1)) {
            this.insert(dbParam);
        } else {
            dbParam.setId(oldSangerHschyq1.getId());
            this.update(dbParam);
        }
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .experimentProcessId(sangerId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(sangerId)
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .op(String.format("%s%s-%s", sanger.getName(), sanger.getProcessNumber(), SangerStatusEnum.HSCHYQ1.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

    @Override
    public Integer count(SangerHschyq1SearchVo sangerHschyq1SearchVo) {
        return mapper.count(sangerHschyq1SearchVo);
    }

    @Override
    public List<SangerHschyq1Vo> selectList(SangerHschyq1SearchVo sangerHschyq1SearchVo) {
        return mapper.selectList(sangerHschyq1SearchVo);
    }

    @Override
    public Page<SangerHschyq1Vo> selectPage(SangerHschyq1SearchVo sangerHschyq1SearchVo) {
        //先直接查总数
        int count = count(sangerHschyq1SearchVo);
        //分页
        Page<SangerHschyq1Vo> page = new Page<>(true, count, sangerHschyq1SearchVo.getPageNum(), sangerHschyq1SearchVo.getPageSize());
        sangerHschyq1SearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<SangerHschyq1Vo> responseVos = this.selectList(sangerHschyq1SearchVo);
        page.setData(responseVos);
        return page;
    }

}